import request from '../request';
import checkError from './checkGizwitsError';

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function gizRequest(url: string, options: IRequestOptions) {
  return request(url, { timeout: 10 * 1000, ...options }).then(
    (response: any) => response.text().then(
      (text: string) => {
        let data = text;
        try {
          data = JSON.parse(text);
        } catch (ex) {
          checkError(ex.errorCode);
          console.log('error!!!!', ex.message);
        }
        if (response.ok) {
          console.log(`openApi result ${url}`, data);
        } else {
          console.log(`openApi result ${url}`, data);
        }
        return {
          data,
          status: response.status,
          success: response.ok,
        };
      },
  ).catch((err: any) => {
    return {
      data: { err },
      success: false,
    };
  });
}
